package com.fecean.aabbc.netty.ssl;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.io.ClassPathResource;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

/**
 * SSLEngineFactory
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-08-14 10:55
 * @blame Team
 */
public class SSLEngineFactory {

    public static final String PROTOCOL_TLS = "TLS";

    public static KeyManagerFactory getKeyManagerFactory(String path, String keyPass, String storePass){
        KeyManagerFactory factory = null;
        try (FileInputStream is = new FileInputStream((new ClassPathResource(path)).getFile())){
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(is, keyPass.toCharArray());
            factory = KeyManagerFactory.getInstance("SunX509");
            factory.init(ks, storePass.toCharArray());
        } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException e) {
            ExceptionUtils.rethrow(e);
        }
        return factory;
    }

    public static TrustManagerFactory getTrustManagerFactory(String path, String keyPass) {
        TrustManagerFactory factory = null;
        try (FileInputStream is = new FileInputStream((new ClassPathResource(path)).getFile())){
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(is, keyPass.toCharArray());
            factory = TrustManagerFactory.getInstance("SunX509");
            factory.init(ks);
        } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
            ExceptionUtils.rethrow(e);
        }
        return factory;
    }
}
